import { App } from './app';
import Util from './util';
import { Page } from './page';
import './dx-ext';

let orderType = [{name:'全部类型', id:''}, {name:'普通订单', id:'general'}, {name:'赠送订单', id:'gift'}];
let orderState = [{name:'全部状态', id:''}, {name:'待支付', id: 0}, {name:'待发货', id:1}, {name:'已取消', id:2}, {name:'未领取',id:3}, {name:'已过期',id:4}, {name:'已发货',id:5}, {name:'已完成',id:6},{name:'交易关闭',id:7},{name:'已领取待使用',id:8},{name:'已过期退款中',id:9},{name:'已过期已退款',id:10}];

let filterExpr = {}, searchTextBoxInstance;
let applyFilterExpr = (ds,applyFilter=false) => {
	let arr = [];

	if (filterExpr.type) {
		arr.push(['type', '=', filterExpr.type]);
	}

	if (filterExpr.state||filterExpr.state===0) {
		arr.push(['state', '=', filterExpr.state]);
	}

	if (filterExpr.start) {
		arr.push(['created_at', '>=', filterExpr.start]);
	}

	if (filterExpr.end) {
		arr.push(['created_at', '<=', filterExpr.end]);
	}
	
	if(applyFilter){ return arr};

	if (arr.length) ds.filter(arr);
	else ds.filter(null);

	
}

App.registerCrud({
	route: 'order',
	url: $.config('apiUrl') + 'restful?_model=order',
	title: '订单',
	placeholder: '订单号或葡萄酒名称',
	capable: {
		create: true
	},
	grid: {
		selection: {
			mode: 'none'
		},
		columnAutoWidth:true,
		showRowLines:true,
		wordWrapEnabled:true
	},
	search:{
		mobile:'out_trade_no'
	},
	toolbar:{
		items:[{
			location: 'before',
			widget: 'dxTextBox',
			options: {
				width: 300,
				placeholder: '请输入订单号或葡萄酒名称进行搜索',
				onInitialized: function(e) {
					searchTextBoxInstance = e.component;
				}
			}
		}, {
			location: 'before',
			widget: 'dxButton',
			options: {
				text: '查询',
				onClick: function(e) {
					var ds = App.crudGridInstance().option('dataSource');

					ds.searchExpr(['out_trade_no', 'product_chname', 'product_name']);
					ds.searchValue(searchTextBoxInstance.option('value'));

					ds.reload();
				}
			}
		}, {
			location: 'after',
			widget: 'dxSelectBox',
			options: {
				dataSource: orderType,
				valueExpr: 'id',
				displayExpr: 'name',
				value: orderType[0].id,
				onValueChanged: function(e) {
					var ds = App.crudGridInstance().option('dataSource');
					
					filterExpr.type = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		}, {
			location:'after',
			widget:'dxSelectBox',
			options: {
				dataSource: orderState,
				valueExpr:'id',
				displayExpr:'name',
				value: orderState[0].id,
				onValueChanged:function(e){
					var ds = App.crudGridInstance().option('dataSource');
console.log(e.value)
					filterExpr.state = e.value;
					applyFilterExpr(ds);

					ds.reload();

				}
			}
		}, {
			location:'after',
			widget:'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '开始时间',
				onValueChanged:function(e){
					var ds = App.crudGridInstance().option('dataSource');

					filterExpr.start = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		},{
			location:'after',
			widget:'dxDateBox',
			options: {
				displayFormat: "yyyy-MM-dd",
				dateSerializationFormat: 'yyyy-MM-dd',
				placeholder: '结束时间',
				onValueChanged:function(e){
					var ds = App.crudGridInstance().option('dataSource');

					filterExpr.end = e.value;
					applyFilterExpr(ds);

					ds.reload();
				}
			}
		},{
			location:'after',
			widget:'dxButton',
			options:{
				text:'导出',
				onClick:function(e){
					var ds = App.crudGridInstance().option('dataSource');
					var url = new Url(API('order-export'));
					let loadOptions = {desc:true,filter:applyFilterExpr(ds,true)};

						url.query._param = JSON.stringify(loadOptions);
console.log(url)
						window.location=url;

						 // $.crudStore(API('order-export')).load({desc:true,filter:applyFilterExpr(ds,true)}).then(res=>{
						 // 	console.log(res)
						 // })
						

					

					// let apply=applyFilterExpr(ds).concat({desc:true});
					// console.log(apply)
					// $.get(API('order-export'),apply,function(res){
					// 	console.log(res)
					// })
				}
			}
		}]
	},
	columns:[{
		dataField:'out_trade_no',
		caption:'订单号'
	},{
		dataField:'origin_qrcode',
		caption:'来源',
		width:40,
		cellTemplate:function(c,e){
			$(c).text(e.value?e.value:'普通')
		}
	},{
		dataField:'create_user.name',
		caption:'付款人',

	},{
		dataField:'get_user.name',
		caption:'收礼人',

	},{
		dataField:'product_name',
	
		caption:'葡萄酒'
	},{
		dataField:'price',
		width:80,
		caption:'单价'
	},{
		dataField:'quantity',
		width:40,
		caption:'数量'
	},{
		dataField:'coupon_fee',
		width:40,
		caption:'优惠券金额',

	},{
		dataField:'total_fee',
		caption:'总价'
	},{
		dataField:'type',
		caption:'类型',
		width:40,
		cellTemplate:function(c,e){
			$(c).text(e.value=='general'?'普通':'礼物')
		}
	},{
		dataField:'address',
		caption:'地址'
	},{
		dataField:'state',
		caption:'状态',
		cellTemplate:function(c,e){
			var text=orderState.filter(function(item){return item.id==e.value&&item.id!==''});
			if(text.length!=0)$(c).text(text[0].name)
		}
	},{
		dataField:'importer_name',
		caption:'进口商'
	},{
		dataField:'created_at',
		caption:'下单时间'
	},{
		dataField:'	state',
		width:80,
		allowSorting:false,
		headerCellTemplate:function(con){
		let $html = $('<label><input type="file" style="display:none"/><a style="text-decoration:underline">批量发货</a></lbael>').appendTo(con)
			$html.find('input').click().change(function(){
				console.log(this);
				var formData = new FormData;
				if(this.files.length > 0){ 
				formData.append('file', this.files[0]);
				$.ajax({
					url:API('order-delivery-batch'),
					type: "POST",
					data: formData,
					processData: false,
					contentType: false
					}).then(function(res){
					if(res && res.status === "success") {
							 DevExpress.ui.notify('上传成功','success',1500);
							 var ds = App.crudGridInstance().option('dataSource');
							 ds.load();
						} else {
							DevExpress.ui.dialog.alert('文件上传失败', '操作失败');
						}
				})
				}
			})
		},
		cellTemplate:function(c,e){
			let logistics={
				out_trade_no:e.data.out_trade_no,
				code:'',
				number:''
			}
			function active(){
				$("<div/>").appendTo($("#popups")).dxPopup({
					title:'请输入',
					visible:true,
					width:450,
					height:360,
					contentTemplate:function(){
						let html = "<form class='is_delivery' style='width:100%''><div class='corporation' style='margin-bottom:20px'></div><div class='product_order' style='margin-bottom:20px;text-align:center'></div><div class='order_button' ></div></form>"
						return html
					},
					onContentReady:function(e){
						console.log(e)
						let $content = e.component.content();
						$content.find(".corporation").dxSelectBox({
							placeholder:"物流公司",
							validationRules: [{
							type: "required"
								}],
							showClearButton:true,
							searchEnabled:true,
							dataSource:$.crudStore(API('restful?_model=express-carrier')),
							displayExpr:'name_cn',
							valueExpr:'code',
							onValueChanged:function(e){
								logistics.code=e.value;
							}
						});
						$content.find('.product_order').dxTextBox({
							placeholder:'物流单号',
							validationRules: [{
							type: "required"
								}],
							value:'',
							onInput:function(e){
								logistics.number=e.component._options.text
							},
							onFocusOut:function(e){
								logistics.number=e.component._options.text
							}
						});
						$content.find(".order_button").dxButton({
							text:'发货',
							type:'success',
							onClick:function(e){
								$.post(API('order-delivery'),
								logistics,
								function(e){
									DevExpress.ui.notify('发货成功','success',1500) ;
									App.crudGridInstance().option('dataSource').load()

								});
								return false
							}
						})
					}
				})
			};

			function check_logistics(ID,name){
				let formData = new DevExpress.data.DataSource({ store:$.crudStore(API("order-express/"+ID))});
				$("<div/>").appendTo($("#popups")).dxPopup({
					width:1000,
					height:600,
					visible:true,
					title:'物流信息',
					onContentReady:function(e){
					let $content = e.component.content();
					$content.css({"overflow-y":"scroll"});
					// let loading=$content.find(".check_logistics").dxLoadPanel({
					// 	message:'loading……',
					// 	visible:true
					// }).dxLoadPanel('instance');
					$.get(API("order-express/"+ID)).then(res =>{ 
					$content.find(".check_logistics").dxForm({
						formData:res.data,
					    showColonAfterLabel: true,
            			showValidationSummary: false,
            			validationGroup: "crud",
            			alignItemLabels: true,
            			alignItemLabelsInAllGroups: true,
            				items:[
            				    {
            				    	colCount:2,
            				    	itemType:'group',
            				    	items:[{
									dataField:'ChStatus',
									label:{text:'状态'},
									disabled:true
								},{
									dataField:'name',
									label:{text:'收件人'},
									disabled:true
								},{
									dataField:'title',
									label:{text:'产品名称'},
									disabled:true
								},{
									dataField:'out_trade_no',
									label:{text:'订单号'},
									disabled:true
								},{
									dataField:'carrier.name_cn',
									label:{text:'邮局名称'},
									disabled:true
								},{
									dataField:'tracking_number',
									label:{text:'快递单号'},
									disabled:true
								}]
            				    }
            					,{
									
									editorType:'dxDataGrid',
									editorOptions:{
									dataSource:res.data.expressInfo.origin_info.trackinfo,
									columns:[{
										dataField:'Date',
										caption:'日期'
									},{
										dataField:'StatusDescription',
										caption:'状态'
									},{
										dataField:'Details',
										caption:'地点'
									}]
									}
								}]
						}).dxForm("instance").option("formData.name",name)
					})
					},
					contentTemplate:function(){
					let html = "<div class='check_logistics'><div/>";
					return html
					}
				})
			}

		 if(e.data.state == '5'||e.data.state == '6'){
		 	$("<a>").text('查看物流').css({"text-decoration":'underline'}).click(function(){
		 		check_logistics(e.data.id,e.data.username)
		 	}).appendTo(c)
		 }else if(e.data.state == '1' ){
		 	$("<a>").text('发货').css({"text-decoration":"underline"}).click(function(){
		 		active()
		 	}).appendTo(c)
		 }
		}
	}]
})